package cn.fl.warrant.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.api.IProjectQueryApiService;
import cn.fl.project.condition.PrjContCfgDQC;
import cn.fl.project.dto.PrjContCfgDDTO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.warrant.service.IArcBscInfoService;
import cn.fl.warrant.transform.ArcBscInfoVOTransform;
import cn.fl.warrant.vo.ArcBscInfoVO;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import fl.warrant.facade.archive.condition.ArcBscInfoQueryCondition;
import fl.warrant.facade.archive.condition.PrjContCfgMQC;
import fl.warrant.facade.archive.constant.ArchiveConstants;
import fl.warrant.facade.archive.dto.ArcBscInfoDTO;

/**
 * @Description: 档案基础信息(旧表：T_Data_List) 控制层
 */
@Controller
@RequestMapping("/archive/arcBscInfo")
public class ArcBscInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ArcBscInfoController.class);
	
	/**
	 * ArcBscInfo 服务层BEAN
	 */
	@Autowired
	private IArcBscInfoService arcBscInfoService;
	@Autowired
	private IProjectQueryApiService projectQueryApiService;
	
	/**
	 * 跳转到档案基础信息列表页面
	 */
	@RequestMapping("/toListPage.do")
	public String toListPage(HttpServletRequest request) {
		
		this.setAttribute(request);
  		
		return "archive/arcBscInfo/arcBscInfoList";
	}

	/**
	 * 查询档案基础信息列表数据
	 */
	@RequestMapping("/initList.do")
	@ResponseBody
	public Object initList(ArcBscInfoQueryCondition qc,HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

//		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
//		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		page.setCondition(qc);
		Pager pager = this.arcBscInfoService.searchListPage(page);
		List<ArcBscInfoVO> list = (List<ArcBscInfoVO>) pager.getResultList();
		return new ListPageVO<ArcBscInfoVO>(list, pager.getTotalCount());
	}

	/**
	 * 不分页查询
	 */
	@RequestMapping("/searchList.do")
	@ResponseBody
	public Object searchList(ArcBscInfoQueryCondition qc,HttpServletRequest request, HttpServletResponse response) {
		
		List<ArcBscInfoDTO> arcBscInfoDTOList = this.arcBscInfoService.searchList(qc);
		List<ArcBscInfoVO> arcBscInfoVOList = ArcBscInfoVOTransform.toVOList(arcBscInfoDTOList);
		return new ListPageVO<ArcBscInfoVO>(arcBscInfoVOList, arcBscInfoVOList.size());
	}
	
	/**
	 * 跳转到保存页面(新增和修改)
	 */
	@RequestMapping(value = "/toSave.do")
	public Object toSave(HttpServletRequest request, HttpServletResponse response) {
		
		this.setAttribute(request);
		
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)) {
			request.setAttribute("entity", arcBscInfoService.selectById(Long.valueOf(id)));
		}
		
		return "archive/arcBscInfo/arcBscInfoSave";
	}

	
	/**
	 * 新增和修改
	 */
	@RequestMapping(value = "/save.do")
	@ResponseBody
	public Object save(ArcBscInfoVO entity,HttpServletRequest request, HttpServletResponse response){
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
			
			if(StringUtils.isBlank(entity.getWarrantName())) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("请填写权证名称");
				return result;
			}
			entity.setWarrantName(entity.getWarrantName().trim());
			/**
			 * 按照合同号展示：合同资料、承租人资料、担保人资料；
				 * 按照支付表分别展示：权证资料；
			 */
			if("3".equals(entity.getWarrantType()) 
					|| "5".equals(entity.getWarrantType()) ) {//权证资料，按照支付表展示
				entity.setArcLevel("2");
			}else {//其他资料，按照合同展示
				entity.setArcLevel("1");
			}
			
			//如果不是电子资料，不保存电子资料配置编号和子编号
			if("no".equals(entity.getIsEle())) {
				entity.setCfgCd("");
				entity.setCfgDtlCd("");
			}
			
			if(entity.getId() == null) {//新增
				
				//验证权证名称不能重复
				ArcBscInfoQueryCondition condition = new ArcBscInfoQueryCondition();
				condition.setWarrantName(entity.getWarrantName());
				condition.setWarrantType(entity.getWarrantType());
				List<ArcBscInfoDTO> arcBscInfoDTOList = arcBscInfoService.searchList(condition);
				if(arcBscInfoDTOList != null && arcBscInfoDTOList.size() >0) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("权证名称已存在");
					return result;
				}
				
//				entity.setIsValid(ArchiveConstants.IS_VALID);
				entity.setIsDel(ArchiveConstants.IS_DEL);
				entity.setCrtTm(new Date());
				entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				
				Long id = this.arcBscInfoService.add(entity);
				result.setData(id);
				
			}else {//修改
				
				ArcBscInfoVO arcBscInfoVO = arcBscInfoService.selectById(entity.getId());
				if(arcBscInfoVO != null) {
					
					//验证权证名称不能重复
					ArcBscInfoQueryCondition condition = new ArcBscInfoQueryCondition();
					condition.setWarrantName(entity.getWarrantName());
					condition.setWarrantType(entity.getWarrantType());
					List<ArcBscInfoDTO> arcBscInfoDTOList = arcBscInfoService.searchList(condition);
					if(arcBscInfoDTOList != null && arcBscInfoDTOList.size() >0) {
						for (ArcBscInfoDTO arcBscInfoDTO : arcBscInfoDTOList) {
							if(arcBscInfoDTO.getId() != null && !arcBscInfoDTO.getId().equals(arcBscInfoVO.getId())) {
								result.setSuccess(BaseConstant.IS_YESNO_NO);
								result.setInfo("权证名称已存在");
								return result;
							}
						}
					}
					
					arcBscInfoVO.setArcLevel(entity.getArcLevel());
					arcBscInfoVO.setCfgCd(entity.getCfgCd());
					arcBscInfoVO.setCfgDtlCd(entity.getCfgDtlCd());
					arcBscInfoVO.setIsEle(entity.getIsEle());
					arcBscInfoVO.setWarrantName(entity.getWarrantName());
					arcBscInfoVO.setWarrantType(entity.getWarrantType());
					arcBscInfoVO.setIsValid(entity.getIsValid());
					arcBscInfoVO.setMdfTm(new Date());
					arcBscInfoVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
					
					this.arcBscInfoService.update(arcBscInfoVO);
					result.setInfo(SysLogConstant.LOG_CMM_UPDATE_SUCC);
				}
			}
			
			BaseLogUtils.info(logger, "save", "操作数据. DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "save", "操作数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "save", "操作数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	
	
	
	/**
	 * 流程审批附加页面
	 */
	@RequestMapping(value = "/toView.do")
	public Object toView(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String isFlow = request.getParameter("isFlow");//是否流程附加信息页面标识
		
		this.setAttribute(request);
		
		return "archive/arcBscInfo/arcBscInfoAdd";
	}
	
	
	
	
	
	
	
	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do")
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.arcBscInfoService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	private void setAttribute(HttpServletRequest request) {
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		//权证类别
		request.setAttribute("warrantTypeList", arcBscInfoService.getKvList(sysCd, orgCd, ArchiveConstants.ARC001));
		//归类级别
//		request.setAttribute("arcLevelList", arcBscInfoService.getKvList(sysCd, orgCd, ArchiveConstants.ARC004));
		//项目合同配置编号
		request.setAttribute("cfgCdList", arcBscInfoService.selectPrjContCfgList(new PrjContCfgMQC()));
		
	}

	
	/**
	 * 交接单选择基础档案资料页面
	 */
	@RequestMapping(value = "/arcBscInfoSelect.do")
	public Object arcBscInfoSelect(HttpServletRequest request) {
		
		return "archive/arcBscInfo/arcBscInfoSelect";
	}
	
	
	/**
	 * 项目合同配置子编号
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/selectCfgDtlCdList.do")
	@ResponseBody
	public Object selectCfgDtlCdList(HttpServletRequest request) throws BaseException {
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_NO, SysLogConstant.LOG_CMM_OPERATE_FAIL);
		try {
			String code = request.getParameter("code");
			if(StringUtils.isNotBlank(code)){
				
				PrjContCfgDQC  qc = new PrjContCfgDQC();
				
				List<String> cfgCdList = new ArrayList<String>();
				cfgCdList.add(code);
				
				qc.setCfgCdList(cfgCdList);
				qc.setIsDel(ArchiveConstants.IS_DEL);
				List<PrjContCfgDDTO> prjContCfgDDTOList = projectQueryApiService.searchPrjContCfgDDTOList(qc);
				
				if(CollectionUtils.isNotEmpty(prjContCfgDDTOList)){
					result.setData(JSONArray.toJSON(prjContCfgDDTOList));
				}
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				BaseLogUtils.info(logger, "selectCfgDtlCdList", "获取数据成功."+prjContCfgDDTOList, CurrentThreadContext.getCurrentUserName());
			}
			
		}catch(BaseException ex) {
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "selectCfgDtlCdList", "获取-失败."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "selectCfgDtlCdList", "获取失败."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}

